<template>
  <BasicTable @register="registerCategoryTable" :searchInfo="searchInfo" :canResize="true">
    <template #cid="{ record }">
      {{ returnChannelName(record) }}
    </template>
    <template #tablecode="{ record }">
      {{ returnTableName(record) }}
    </template>
    <template #toolbar>
      <a-button type="primary" @click="onAddCategoryButtonClick">新增分类</a-button>
    </template>
    <template #action="{ column, record }">
      <TableAction
        :actions="[
          {
            icon: 'clarity:note-edit-line',
            tooltip: '编辑',
            onClick: onEditCategoryButtonClick.bind(null, record),
          },
          {
            icon: 'ant-design:delete-outlined',
            color: 'error',
            tooltip: '删除',
            popConfirm: {
              title: '是否确认删除',
              placement: 'left',
              confirm: onDeleteCategoryButtonClick.bind(null, record),
            },
          },
          {
            label: '关联站点',
            onClick: onOpenStationDrawer.bind(null, record),
          },
        ]"
      />
    </template>
  </BasicTable>
  <AddOrUpdateCategory @register="registerAddOrUpdateCategoryForm" @success="afterSuccess" />
  <StationDrawer @register="registerStationDrawer" />
</template>
<script lang="ts">
  import { defineComponent, ref, onBeforeMount, watch } from 'vue';
  import { queryDBTable } from '/@/api/platform/dbTable';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import { KeyValuePairDto } from '/@/api/model/kvpairModel';
  import AddOrUpdateCategory from './component/AddOrUpdateCategory.vue';
  import { ExchangeCategoryDto } from '/@/api/qms/model/exchangeChannelModel';
  import { getChannelCategory, deleteCategory, queryAllChannel } from '/@/api/qms/exchangeChannel';
  import { categoryTableColumns } from './exchangeCategory.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useDrawer } from '/@/components/Drawer';
  import StationDrawer from './component/CategoryStationDrawer.vue';

  export default defineComponent({
    name: 'CategoryIndex',
    components: {
      BasicTable,
      PageWrapper,
      AddOrUpdateCategory,
      TableAction,
      StationDrawer,
    },
    props: ['searchInfo'],
    setup(props, { emit }) {
      const selectChannelOption = ref<KeyValuePairDto[]>([]);
      const selectDBTableOption = ref<KeyValuePairDto[]>([]);
      const [registerAddOrUpdateCategoryForm, { openModal: openAddOrUpdateForm }] = useModal();
      const [registerStationDrawer, { openDrawer }] = useDrawer();
      const [registerCategoryTable, { reload, setTableData }] = useTable({
        title: '数据分类',
        api: getChannelCategory,
        rowKey: 'id',
        columns: categoryTableColumns,
        ellipsis: true,
        canResize: true,
        immediate: false,
        bordered: true,
        striped: false,
        showTableSetting: true,
        indexColumnProps: {
          width: 0,
        },
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });

      /**
       * 打开新增窗口,将左侧选中的分组传过去
       */
      function onAddCategoryButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '数据分类管理',
          operateType: OperationTypeEnum.ADD,
          channelId: props.searchInfo.id,
        };
        openAddOrUpdateForm(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditCategoryButtonClick(record: ExchangeCategoryDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '数据分类管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
        };
        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 删除数据分类
       * @param record
       */
      function onDeleteCategoryButtonClick(record: ExchangeCategoryDto) {
        deleteCategory(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              reload();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function onOpenStationDrawer(record: ExchangeCategoryDto) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '数据分类',
          operateType: OperationTypeEnum.SET_RELATION,
          dataId: record.id, // 分类ID,要设定指定分类下的关联站点
          dataTitle: record.name,
        };
        openDrawer(true, propsData);
      }

      function returnChannelName(record: ExchangeCategoryDto) {
        for (let i of selectChannelOption.value) {
          if (record.cid === i.value) {
            return i.label;
          }
        }
      }
      function returnTableName(record: ExchangeCategoryDto) {
        for (let i of selectDBTableOption.value) {
          if (record.tablecode === i.value) {
            return i.label;
          }
        }
      }
      /**
       * 新增/编辑弹窗确认操作之后刷新页面
       */
      function afterSuccess(channelId) {
        emit('success', channelId);
        reload();
      }
      onBeforeMount(() => {
        queryAllChannel().then((res) => {
          let Options = [];
          for (let d of res) {
            // 这里要转number类型,因为获取全部参数类型请求回来的数据key为string,而其他接口为Number
            Options.push({ value: d.id, label: d.name });
          }
          selectChannelOption.value = Options;
        });
        queryDBTable({}).then((res) => {
          let Options = [];
          for (let i of res) {
            Options.push({ value: i.code, label: i.name });
          }
          selectDBTableOption.value = Options;
        });
      });
      watch(
        () => props.searchInfo,
        (newVal) => {
          console.log(newVal, 'newVAL');
          setTableData([]);
          reload();
        },
        { deep: true },
      );
      return {
        registerCategoryTable,
        registerAddOrUpdateCategoryForm,
        selectChannelOption,
        selectDBTableOption,
        registerStationDrawer,
        openDrawer,
        onOpenStationDrawer,
        returnTableName,
        returnChannelName,
        afterSuccess,
        onAddCategoryButtonClick,
        onEditCategoryButtonClick,
        onDeleteCategoryButtonClick,
      };
    },
  });
</script>
